﻿using System.Web.Mvc;
using ECGadmin.Utility;
using ECGadmin.WebUI.Infrastructure;
using ECGadmin.WebUI.Models;
using System;

namespace ECGadmin.WebUI.Attributes
{
    public class AdminLoggedAuthorize : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var loginCookie = filterContext.HttpContext.Request.Cookies["loginCookie"];
            if (loginCookie != null)
            {
                var loginCookieGuid = loginCookie["loginCookieGuid"] ;
                var password = loginCookie["loginCookiePass"];
                if(password.CreatePasswordHash(loginCookieGuid) == loginCookie["cookiesHash"])
                {
                    //set session
                    if (filterContext.HttpContext.Session[SessionConfig.SessionAdminLogged] == null)
                    {
                        filterContext.HttpContext.Session[SessionConfig.SessionAdminLogged] = new AdminLoginModel
                        {
                            Id = Convert.ToInt32(loginCookie["Id"]),
                            UserName = loginCookie["UserName"],
                            FullName = loginCookie["FullName"],
                            Email = loginCookie["Email"]
                        };
                    }
                    return;
                }
            }
            if (filterContext.HttpContext.Session[SessionConfig.SessionAdminLogged] == null)
            {
                filterContext.Result = new RedirectResult("/AdminLogin/Login");
            }
        }
    }
}